package com.dragon.graduation.finalDefense.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.config.exception.exception.GlobalException;
import com.dragon.graduation.finalDefense.controller.dto.FinalDefenseAddDTO;
import com.dragon.graduation.finalDefense.controller.dto.FinalDefenseAuditDTO;
import com.dragon.graduation.finalDefense.controller.dto.FinalDefenseSearchDTO;
import com.dragon.graduation.finalDefense.controller.dto.FinalDefenseUpdateDTO;
import com.dragon.graduation.finalDefense.controller.vo.FinalDefenseVO;
import com.dragon.graduation.finalDefense.entity.FinalDefenseEntity;
import com.dragon.graduation.finalDefense.service.FinalDefenseService;
import com.dragon.graduation.midtermDefense.entity.MidtermDefenseEntity;
import com.dragon.graduation.midtermDefense.service.MidtermDefenseService;
import com.dragon.graduation.project.entity.ProjectEntity;
import com.dragon.graduation.project.service.ProjectService;
import com.dragon.graduation.projectProgress.service.ProjectProgressService;
import com.dragon.graduation.user.controller.vo.UserVO;
import com.dragon.jwt.JwtUtil;
import com.dragon.results.page.ResultPage;
import com.dragon.results.result.HttpResult;
import com.dragon.util.MyPage;
import com.dragon.utils.LocalFileUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 终期答辩表 前端控制器
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:18:39
 */
@RestController
@RequestMapping("/finalDefense")
@RequiredArgsConstructor
@Api(tags = "终期答辩表 相关接口")
public class FinalDefenseController {

    private final FinalDefenseService finalDefenseService;
    private final MidtermDefenseService midtermDefenseService;
    private final LocalFileUtil localFileUtil;
    private final ProjectService projectService;
    private final ProjectProgressService projectProgressService;

    @PostMapping("add")
    @ApiOperation("1]终期答辩表添加")
    @ApiOperationSupport(order = 1)
    public HttpResult<String> add(@RequestBody FinalDefenseAddDTO addDTO) {
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);

        MidtermDefenseEntity midtermDefense = midtermDefenseService.findByProjectIdAndStudentId(userVO.getRoleId(), addDTO.getProjectId());
        Assert.isFalse(ObjectUtils.isEmpty(midtermDefense), () -> new GlobalException("您当前题目的中期答辩材料未提交，不可提交终期答辩"));
        Assert.isFalse(midtermDefense.getStatus() != 1, () -> new GlobalException("您当前题目的中期答辩材料未审核通过，不可提交终期答辩记录"));

        FinalDefenseEntity finalDefense = finalDefenseService.findByProjectIdAndStudentId(userVO.getRoleId(), addDTO.getProjectId());
        if (ObjectUtils.isNotEmpty(finalDefense)) {
            String message;
            if (finalDefense.getStatus() == 0) {
                message = "您当前题目的终期答辩记录未审核，不可重复提交";
            } else {
                message = "您当前题目的终期答辩记录已审核通过，不可重复提交";
            }
            localFileUtil.deleteFile(addDTO.getDocumentPath());
            throw new GlobalException(message);
        }
        FinalDefenseEntity entity = FinalDefenseAddDTO.to(addDTO, FinalDefenseEntity.class);
        entity.setDefenseTime(LocalDateTime.parse(addDTO.getDefenseTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        entity.setStudentId(userVO.getRoleId());
        entity.setStatus(0);
        finalDefenseService.save(entity);
        projectProgressService.record(userVO.getRoleId(),entity.getProjectId(),4,0);
        return HttpResult.ok("添加成功");
    }

    @PostMapping("update")
    @ApiOperation("2]终期答辩表修改")
    @ApiOperationSupport(order = 2)
    public HttpResult<String> update(@RequestBody FinalDefenseUpdateDTO updateDTO) {
        FinalDefenseEntity entity = finalDefenseService.getById(updateDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要修改的数据不存在"));
        entity = FinalDefenseUpdateDTO.to(updateDTO, FinalDefenseEntity.class);
        finalDefenseService.updateById(entity);
        return HttpResult.ok("修改成功");
    }

    @PostMapping("search")
    @ApiOperation("3]终期答辩表分页查询")
    @ApiOperationSupport(order = 3)
    public HttpResult<ResultPage<List<FinalDefenseVO>>> search(@RequestBody FinalDefenseSearchDTO searchDTO) {
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        if (userVO.getRole() != 1) {
            if (userVO.getRole() == 2) {
                //学生看自己的开题报告
                searchDTO.setStudentId(userVO.getRoleId());
            } else {
                //老师看自己项目下的所有
                List<ProjectEntity> projectEntities = projectService.findByTeacherId(userVO.getRoleId());
                if (!CollectionUtils.isEmpty(projectEntities)) {
                    List<Integer> collected = projectEntities.stream().map(ProjectEntity::getId).collect(Collectors.toList());
                    searchDTO.setProjectList(collected);
                }
            }
        }

        Page<FinalDefenseEntity> entityPage = MyPage.setPage(FinalDefenseEntity.class, searchDTO.getPage());
        Page<FinalDefenseVO> page = finalDefenseService.findPages(entityPage, searchDTO);
        ResultPage<List<FinalDefenseVO>> resultPage = MyPage.copyPage(page, FinalDefenseVO.class);
        return HttpResult.okForData(resultPage);
    }

    @PostMapping("delete")
    @ApiOperation("4]终期答辩表删除")
    @ApiOperationSupport(order = 4)
    public HttpResult<String> delete(@RequestBody List<Integer> idList) {
        finalDefenseService.removeByIds(idList);
        return HttpResult.ok("删除成功");
    }

    @PostMapping("audit")
    @ApiOperation("5]评审答辩")
    @ApiOperationSupport(order = 5)
    public HttpResult<String> audit(@RequestBody FinalDefenseAuditDTO auditDTO) {
        FinalDefenseEntity entity = finalDefenseService.getById(auditDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要审核的数据不存在"));
        Assert.isFalse(entity.getStatus() != 0, () -> new GlobalException("该答辩已评审;不可重复评审"));
        UserVO userVO = JwtUtil.parseToken(JwtUtil.getTokenFromRequest(), UserVO.class);
        entity.setStatus(auditDTO.getStatus());
        entity.setReviewerId(userVO.getId());
        entity.setReviewTime(LocalDateTime.now());
        entity.setScore(auditDTO.getScore());
        entity.setReviewComment(auditDTO.getReviewComment());
        finalDefenseService.updateById(entity);
        if (entity.getStatus()==1) {
            projectProgressService.record(entity.getStudentId(),entity.getProjectId(),4,1);
        }else {
            projectProgressService.record(entity.getStudentId(),entity.getProjectId(),4,2);
        }
        return HttpResult.ok("评审成功");
    }
}
